package sunwul.datasource.common;

import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/*****
 * @author sunwul
 * @date 2022/2/28 10:12
 * @description 工厂工具类
 */
public class FactoryUtil_manyMybatis {

    /**
     * 创建Mybatis SqlSessionFactory
     *
     * @param dataSource 数据源
     * @param mapperPath mapper.xml文件存放路径
     * @param isPrintLog 是否开启控制台日志  true-是  false-否
     * @return SqlSessionFactory
     * @throws Exception ex
     */
    public static SqlSessionFactory createFactory(DataSource dataSource, String mapperPath, boolean isPrintLog) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 指定数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        System.out.println("指定数据源:" + dataSource.getConnection().getMetaData().getURL());
        // 指定Mapper.xml文件
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(mapperPath));
        System.out.println("扫描并装载Mapper.xml文件: " + mapperPath);
        // 启用控制台日志
        if (isPrintLog) {
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setLogImpl(StdOutImpl.class);
            System.out.println("启用控制台日志...");
            sqlSessionFactoryBean.setConfiguration(configuration);
        }

        return sqlSessionFactoryBean.getObject();
    }
}
